package com.aididi.service.impl;

import com.aididi.bean.RedisKeyPrefix;
import com.aididi.exception.BusinessException;
import com.aididi.service.TokenService;
import com.aididi.util.ApiResult;
import com.aididi.util.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Auther: zx.xu
 * @Description:
 */
@Service
public class TokenServiceImpl implements TokenService{



    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String createToken() {
        String token = UUID.randomUUID().toString();
        StringBuilder sb = new StringBuilder();
        sb.append(RedisKeyPrefix.TOKEN_PREFIX).append(token);
        try {
            redisUtil.setEx(sb.toString(),sb.toString(),1000L);
            boolean empty = StringUtils.isEmpty(token);
            if(!empty){
                return token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(RedisKeyPrefix.TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {
            token  = request.getParameter(RedisKeyPrefix.TOKEN_NAME);
            if(StringUtils.isEmpty(token)){
                throw new BusinessException(ApiResult.BADARGUMENT);
            }
        }
        if(!redisUtil.exists(token)){
            throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
        }
        boolean remove = redisUtil.remove(token);
        if (!remove) {
            throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
        }
        return true;
    }
}
